<?php
/**
 * @copyright TinyWEB CMS
 * @link http://tinywebcms.ru
 * @link http://cms.vingrad.ru
 *
 */
class ApplicationViewableController extends ApplicationController implements IViewable
{
    /**
     * View Engine
     *
     * @var IView
     */
    protected $view = null;

    /**
     * Controllers collection
     *
     * @var array
     */
    protected $controllers = array();
    
    final public function __construct()
    {
        $this->view = Registry::get('View');
        $this->view->assign('view', $this->view);
        $this->onConstruct();
    }
    
    public function onConstruct() {}
    
    public function attach(Object $controller, $name = null)
    {
        $controller->prepare();
        
        if($controller instanceof INeedsParentObject) {
            $controller->setParent($this);
        }
        
        if($controller instanceof IExecutable) {
            $controller->exec();
        }
        
        $this->view->assign($name ? $name : get_class($controller), $controller);
    }
    
    public function detach($name)
    {
        $this->view->assign($name, null);
    }
    
    public function push(IViewable $controller)
    {
        $this->controllers[] = $controller;
    }
    
    public function flush()
    {
        $output = array();
        foreach ($this->controllers as $controller) {
            if($controller instanceof ApplicationController) {
                $controller->prepare();
            }
            
            if($controller instanceof INeedsParentObject) {
                $controller->setParent($this);
            }
            
            if($controller instanceof IExecutable) {
                $controller->exec();
            }
            
            if($controller instanceof IViewable) {
                $output[] = $controller->display();
            }
        }

        return join('', $output);
    }
    
    public function getTemplateName()
    {
        return str_replace('Controller', '', $this->getInstanceName()) . '.tpl';
    }

    public function display()
    {
        return sizeof($this->controllers) ? $this->flush() : $this->view->fetch($this->getTemplateName());
    }
}

?>